#!/usr/bin/env python
# -*-coding: utf-8 -*-

"""
ARCRA project OCS demo client
Version 0.2
Programmed by Seunghwan Kim
Last updated : January 31st, 2013

Server log : http://www.arcra.net/log.php
"""

import urllib, httplib
import sqlite3
import string, datetime
import xml.etree.ElementTree as ET
import random

# Global variables

arcra_host = 'www.arcra.net'
prompt = "'l':List, Number:Select, 'h':help, 'q': quit> "
cpid = 0
# Hosptal number is assigned randomly
hid = random.randint(1, 4)
study = {'a': 'Abdominal Pelvic CT', 'b': 'Brain CT', 'c': 'Chest CT', 'x': 'Chest X-ray'}
base_dose = {'a': 25.0, 'b': 4.0, 'c': 6.0, 'x': 0.05}

# Database connection

con = sqlite3.connect("client_demo_data.db")
cur = con.cursor()


def isInt(i):
    try:
        int(i)
        return True
    except ValueError:
        return False

def calAge(dob):
    today = datetime.datetime.today()
    age = today.year - dob.year
    if (today.month > dob.month or (today.month == dob.month and today.day >= dob.day)):
        return age
    else:
        return age - 1

def getTotalDose(pid):
    params = urllib.urlencode({'pid': pid, 'hid': hid})
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    conn = httplib.HTTPConnection(arcra_host)
    conn.request("POST", "/get_total_dose.php", params, headers)
    response = conn.getresponse()
    data = response.read()
    arcra = ET.fromstring(data)
    dose = arcra.findtext('dose')
    risk = arcra.findtext('risk')

    return dose, risk

def printPatientList():
    query = "SELECT pid, name, dob, sex FROM patients"
    cur.execute(query)
    print "%-6s %-20s %-3s %-2s" % ('Number', 'Name', 'Age', 'Sex')
    for row in cur:
        dob = datetime.datetime.strptime(row[2], '%Y-%m-%d')
        age = calAge(dob)
        print "%6s %-20s %3s %2s" % (str(row[0]), row[1], str(age), row[3])

def orderRad(cpid, order):
    # Check arguments and assign modality

    if order in ['a', 'b', 'c']:
        modality = 'CT'
    elif order == 'x':
        modality = 'X-ray'
    else:
        return False

    # Random dose generation

    new_dose = base_dose[order] * random.uniform(0.8, 1.2)

    (dose, risk) = getTotalDose(cpid)

    print "Accumulated exposed radiation is %4.2fmSv, and cancer risk is %2.2f%%" % (float(dose), float(risk))
    while True:
        answer = raw_input("Proceed? (Y, N) ")
        if string.lower(answer) == 'y':
            params = urllib.urlencode({'pid': cpid, 'hid': hid, 'dose': new_dose, 'modality': modality, 'name': study[order]})
            headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
            conn = httplib.HTTPConnection(arcra_host)
            conn.request("POST", "/add_new_study.php", params, headers)
            response = conn.getresponse()
            data = response.read()
            if data[0:5] == 'Order':
                print data
                return True
            else:
                print "Server connection error"
                print "Error message: %s" % data
                return False
        elif string.lower(answer) == 'n':
            print "Order canceled"
            return False
        else:
            continue

"""
Main Program Loop
"""

while True:
    command = raw_input(prompt)
    if command in ['q', 'Q'] or string.lower(command) == 'quit':
        break
    elif command in ['l', 'L'] or string.lower(command) == 'list':
        printPatientList()
    elif isInt(command):
        query = "SELECT pid, name FROM patients WHERE pid=%s" % command
        cur.execute(query)
        row = cur.fetchone()
        if row:
            print "Patient " + row[1] + " was selected"
            cpid = int(command)
        else:
            print "Wrong patient number"
    elif command in ['a', 'A', 'b', 'B', 'c', 'C', 'x', 'X']:
        if cpid == 0:
            print "Select patient first!"
            continue
        else:
            orderRad(cpid, string.lower(command))
    elif command in ['s', 'S'] or string.lower(command) == 'show':
        if cpid == 0:
            print "Select patient first!"
            continue
        else:
            (dose, risk) = getTotalDose(cpid)
            print "Accumulated exposed radiation is %4.2fmSv, and cancer risk is %2.2f%%" % (float(dose), float(risk))
    elif command in ['h', 'H', '?'] or string.lower(command) == 'help':
        print """'l' : Patient list
Number : Select patient
'a' : Abdominal pelvic CT (after select patient)
'b' : Brain CT (after select patient)
'c' : Cehst CT (after select patient)
'x' : Chest X-ray (after select patient)
's' : Show accumulated exposed radiation dose
'q' : Quit program
'h' : Print this help"""
    else:
        print "Unknown command"

# Close DB connection

con.close()
